import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer04 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 1. 启动TCP服务器，监听端口8989
            serverSocket = new ServerSocket(8989);
            System.out.println("服务器启动成功，端口：8989");

            while (true) {
                // 2. 接受客户端连接
                final Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接成功：" + clientSocket.getRemoteSocketAddress());

                // 3. 为每个客户端创建独立线程
                new Thread(() -> {
                    try (
                        // 使用 try-with-resources 管理流
                        BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))
                    ) {
                        String message;
                        while ((message = br.readLine()) != null) {
                            // 4. 处理客户端消息
                            if ("quit".equalsIgnoreCase(message)) {
                                System.out.println("客户端请求退出：" + clientSocket.getRemoteSocketAddress());
                                break;
                            }

                            // 5. 反转字符串并返回
                            String reversed = new StringBuilder(message).reverse().toString();
                            bw.write(reversed);
                            bw.newLine();
                            bw.flush();

                            System.out.println("收到消息: " + message + " → 返回: " + reversed);
                        }
                    } catch (IOException e) {
                        System.err.println("客户端通信异常: " + e.getMessage());
                    } finally {
                        // 6. 关闭客户端连接
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            System.err.println("关闭客户端连接失败: " + e.getMessage());
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        } finally {
            // 7. 关闭服务器
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                    System.out.println("服务器已关闭");
                } catch (IOException e) {
                    System.err.println("关闭服务器失败: " + e.getMessage());
                }
            }
        }
    }
}